package hrhq.cntvcn.utils;

import java.io.IOException;
import java.nio.file.Path;

import org.apache.log4j.Logger;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.impl.CloudSolrClient;
import org.apache.solr.client.solrj.impl.ZkClientClusterStateProvider;
public class SolrUtils {

	PropertiesConfigUtil propertiesConfigUtil = PropertiesConfigUtil.getInstance("solrconfig/solr.properties");
	public SolrUtils() {
		zkHost=propertiesConfigUtil.getValue("zkHost");
		defaultCollection=propertiesConfigUtil.getValue("defaultCollection");
		zkConnectTimeout=Integer.parseInt(propertiesConfigUtil.getValue("zkConnectTimeout"));
		zkClientTimeout=Integer.parseInt(propertiesConfigUtil.getValue("zkClientTimeout"));
		//System.out.println(zkHost);
	}
	
	private static Logger logger = Logger.getLogger(SolrUtils.class);
	private static String zkHost = null;
	private static String defaultCollection = null;
	private static int zkConnectTimeout = 20000;
	private static int zkClientTimeout = 1000;
	private static CloudSolrClient cloudSolrClient = null;
	
	/**
	 * 取得solrClient客户端
	 * 
	 * @return SolrClient
	 */
	public SolrClient getZkSolrClient() {
		logger.info("连接solr cloud,zkhost={ " + zkHost + "}");
		if (cloudSolrClient == null) {
			cloudSolrClient = new CloudSolrClient.Builder().withZkHost(zkHost).build();
		}
		if (defaultCollection != null) {
			cloudSolrClient.setDefaultCollection(defaultCollection);
		}
		cloudSolrClient.setZkClientTimeout(zkClientTimeout);
		cloudSolrClient.setZkConnectTimeout(zkConnectTimeout);
		return cloudSolrClient;
	}

	/**
	 * 上传配置文件到zookeeper
	 * 
	 * @param configPath
	 * @param configName
	 * @return 
	 */
	public boolean uploadconfig(Path configPath, String configName) {
		ZkClientClusterStateProvider zkClientClusterStateProvider = new ZkClientClusterStateProvider(zkHost);
		try {
			zkClientClusterStateProvider.uploadConfig(configPath, configName);
			return true;
		} catch (IOException e) {
			logger.error("上传配置文件失败：", e);
			e.printStackTrace();
		}
		return false;
	}
}
